// 附件工具函数
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';
import { ElMessage } from 'element-plus';
import type { TableConfigItem } from '@com/Table/index';
import request from '@u/request/index';

import ExcelIcon from '@/assets/svg/fileIcon/excel.svg';
import PdfIcon from '@/assets/svg/fileIcon/pdf.svg';
import PptIcon from '@/assets/svg/fileIcon/ppt.svg';
import ImageIcon from '@/assets/svg/fileIcon/image.svg';
import TxtIcon from '@/assets/svg/fileIcon/txt.svg';
import WordIcon from '@/assets/svg/fileIcon/word.svg';

//导出excel附件
export function exportXLSX(
  tableData: any,
  tableOptions: Array<TableConfigItem>,
  title: string = '表',
) {
  //表格数据组装成导出插件要求格式
  let exportData = [];
  for (let i = 0; i < tableData.length; i++) {
    let rowObj = tableData[i];
    let keyObj = {};
    for (let j = 0; j < tableOptions.length; j++) {
      let itemOpt = tableOptions[j];
      if (rowObj.hasOwnProperty(itemOpt.prop)) {
        keyObj[itemOpt.label] = rowObj[itemOpt.prop];
      }
    }
    exportData[i] = keyObj;
  }

  const fileName = `${title}.xlsx`;
  ElMessage.success(`${fileName} 导出中...`);
  // 创建一个工作簿对象
  const workbook = XLSX.utils.book_new();
  // 添加数据到工作簿中
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  let excelData = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  var link = document.createElement('a');
  link.style.display = 'none';
  link.href = URL.createObjectURL(new Blob([excelData], { type: 'application/vnd.ms-excel' }));
  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();
}

export function exportXLSX2(title: any) {
  var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
  var wb = XLSX.utils.table_to_book(document.querySelector('#exportTab'), xlsxParam);
  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: true,
    type: 'array',
  });
  try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${title}.xlsx`);
  } catch (e) {
    if (typeof console !== 'undefined') {
      console.log(e, wbout);
    }
  }
  return wbout;
}

//附件预览
export function previewHandler(data?: any, fileUrl?: any) {
  //附件最大阈值
  const maxBytes = 10 * 1024 * 1024; //10M
  if (data.hasOwnProperty('size') && data.size > maxBytes) {
    return ElMessage('文件过大不支持在线预览，请下载后查看');
  } else {
    const _path = fileUrl.replace('https', 'http');
    const filename: any = fileUrl.split('/').pop();
    const fileExtension = filename.split('.').pop().toLowerCase();
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

    if (getIconList(fileExtension) == 'otherFile') {
      ElMessage('该文件格式不支持在线预览，请下载后查看');
    } else {
      if (
        imageExtensions.includes(fileExtension) ||
        fileExtension == 'txt' ||
        fileExtension == 'pdf'
      ) {
        window.open(_path, '_blank'); //图片、txt、 pdf类型，直接打开
      } else {
        window.open(
          `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(
            _path,
          )}&wdOrigin=BROWSELINK`,
          '_blank',
        );
      }
    }
  }
}

// 附件下载
export async function downloadFile(fileUrl: string, fileName: string = '附件') {
  try {
    // fileUrl="http://s5ot455zh.hd-bkt.clouddn.com/docker-compose.yml?e=1702609211&token=npnRZvfwoJFsZtmuoO1igJf0FDoS7rxgOPYiaIAJ:kmVWJb_-X_ZN56Kj6r4G00leWJ8=";
    const response = await request.get(fileUrl, {
      responseType: 'blob', // 告诉 Axios 返回的数据是一个 Blob 对象
    });
    const url = window.URL.createObjectURL(new Blob([response.data])); // 创建一个临时的 URL 对象
    const link = document.createElement('a'); // 创建一个 <a> 标签元素
    link.href = url;
    link.setAttribute('download', fileName); // 设置下载的文件名
    document.body.appendChild(link); // 将 <a> 标签添加到页面中
    link.click(); // 模拟点击 <a> 标签进行下载
    document.body.removeChild(link); // 下载完成后，移除 <a> 标签和临时的 URL 对象
    window.URL.revokeObjectURL(url);
  } catch (error) {
    ElMessage.error('文件下载失败：' + error);
  }
}

// 打印
export function onPrintHandler() {
  // 获取需要打印的DOM元素
  const printDom = document.getElementById('printMe').parentElement;
  const printContents = printDom.innerHTML;
  // 创建一个新的HTML文档片段来存放要打印的内容
  const originalContents = document.body.innerHTML;
  // 将body内容替换为需要打印的内容
  document.body.innerHTML = printContents;
  // 打印完成后，恢复原来的body内容
  setTimeout(() => {
    document.body.innerHTML = originalContents;
  }, 1000);
  // alert('请在打印弹窗中将缩放比例设置为20%');
  // 调用打印功能
  window.print();
}

interface FileTypes {
  excel: string;
  pdf: string;
  word: string;
  image: string;
  ppt: string;
  txt: string;
  otherFile: string;
}

//附件类型背景颜色
export const Screen_Frame_Colour: FileTypes = {
  excel: '#EB7967',
  pdf: '#4A75AF',
  word: '#6E6F70',
  image: '#4A75AF',
  ppt: '#FEB344',
  txt: '#c2edd9',
  otherFile: '#c886c2',
};

//获取图标
export function getIconList(icon: string): string {
  const iconTypes = {
    word: 'word',
    ppt: 'ppt',
    pdf: 'pdf',
    excel: 'excel',
    xlsx: 'excel',
    xls: 'excel',
    txt: 'txt',
    doc: 'word',
    docx: 'word',
    png: 'Image',
    jpg: 'Image',
  };

  return iconTypes[icon];
}

export function getIconImage(icon: string) {
  const iconTypes = {
    word: WordIcon,
    ppt: PptIcon,
    pdf: PdfIcon,
    excel: ExcelIcon,
    xlsx: ExcelIcon,
    xls: ExcelIcon,
    txt: TxtIcon,
    doc: WordIcon,
    docx: WordIcon,
    png: ImageIcon,
    jpg: ImageIcon,
  };
  return iconTypes[icon];
}
